package com.autumn.platform.core.logger.impl;

import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import org.slf4j.event.Level;

import com.autumn.platform.core.Utils;
import com.autumn.platform.core.logger.LogLevelUpdater;

public class JdkLevelUpdater implements LogLevelUpdater {

    @Override
    public void update(String prefix, Level level) {
        boolean noPrefix = Utils.isBlank(prefix);
        LogManager logManager = LogManager.getLogManager();
        Enumeration<String> enumeration = logManager.getLoggerNames();
        java.util.logging.Level newLevel = convertLevel(level);
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            if (noPrefix || name.startsWith(prefix)) {
                logManager.getLogger(name).setLevel(newLevel);
            }
        }
    }

    @Override
    public void set(String name, Level level) {
        LogManager.getLogManager().getLogger(name).setLevel(convertLevel(level));
    }

    @Override
    public void setRootLevel(Level level) {
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).setLevel(convertLevel(level));
    }

    @Override
    public Set<String> getLogNames() {
        Set<String> names = new LinkedHashSet<>();
        LogManager logManager = LogManager.getLogManager();
        Enumeration<String> enumeration = logManager.getLoggerNames();
        while (enumeration.hasMoreElements()) {
            names.add(enumeration.nextElement());
        }
        return names;
    }

    /**
     * @param level
     * @return
     */
    private java.util.logging.Level convertLevel(Level level) {
        java.util.logging.Level newLevel = java.util.logging.Level.parse(level.toString());
        return newLevel;
    }
}
